// 分块上传（简化版，移除进度条依赖）
import axiosInstance from './request'
export async function multipartUpload(file) {
  const fileSize = file.size
  const CHUNK_SIZE = 5 * 1024 * 1024 // 5MB 分片大小

  try {
    const totalChunks = Math.max(1, Math.ceil(fileSize / CHUNK_SIZE))
    console.log(`文件大小: ${fileSize} 字节, 分片数量: ${totalChunks}`)
    let formData = new FormData()
    formData.append('file', file)
    formData.append('bucket', 'video')
    // 请求后端初始化分片上传，获取 uploadId 和 objectName
    const initResponse = await axiosInstance.post(
      '/video/init-upload',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    const { uploadId, objectName } = initResponse.data.data
    console.log(uploadId, objectName)

    // 2. 分块上传
    for (let i = 0; i < totalChunks; i++) {
      const start = i * CHUNK_SIZE
      const end = Math.min(start + CHUNK_SIZE, fileSize)
      const chunk = file.slice(start, end)

      const formData = new FormData()
      formData.append('bucketName', 'video')
      formData.append('objectName', objectName)
      formData.append('partNumber', i + 1)
      formData.append('uploadId', uploadId)
      formData.append('file', chunk)

      await axiosInstance.post('/video/upload-chunk', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
    }

    // 3. 合并分片
    const completeResponse = await axiosInstance.post(
      '/video/complete-upload',
      {
        bucketName: 'video',
        objectName: objectName,
        uploadId: uploadId
      }
    )

    return completeResponse
  } catch (error) {
    console.error('视频上传失败:', error)
    throw error // 将错误抛给调用者处理
  }
}
